package com.ricky.netty.demo.fileclient;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 接收端,发送端必须告诉接收端文件size
 */
class ChunkedReadHandler extends ChannelHandlerAdapter {
     private long fileSize;
     private File file;
     private FileOutputStream ofs;
     private long readedSize=0;
     public ChunkedReadHandler(long size) throws FileNotFoundException {
         this.fileSize=size;
         this.file = new File("2.zip");
         ofs=new FileOutputStream(this.file);
     }
     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
 
         ByteBuf buf= (ByteBuf) msg;
 
         readedSize +=buf.readableBytes();
         if(buf.isReadable()){
             byte[] bytes=new byte[buf.readableBytes()];
             buf.readBytes(bytes);
             ofs.write(bytes);
         }
 
         System.out.println(fileSize + "   " + readedSize);
 
         if(readedSize >= fileSize){
             ctx.pipeline().remove(this);
             ofs.close();
         }
         buf.release();
     }
 }